package samples.quotes;


import java.util.Hashtable;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.XPathException;

import br.cin.ufpe.in1118.middleware.distribution.message.SOAPFactory;
import br.cin.ufpe.in1118.middleware.distribution.services.util.MiddlewareUtil;
import br.cin.ufpe.in1118.middleware.exceptions.RemoteException;

public final class Quotes_SF extends SOAPFactory {

	@Override
	public Object fromSOAP(String operation, String soapMessage) throws RemoteException {
		Element rootElement = null;
		try {
			rootElement = createRootElement(soapMessage);

			Element response = (Element) rootElement.selectSingleNode("//getQuoteReturn");
			if (response != null) {
				List<?> items = response.elements("item");
				Hashtable<String, String> hash = new Hashtable<String, String>();
				for (Object obj : items) {
					if (obj instanceof Element) {
						Element key = ((Element) obj).element("key");
						Element value = ((Element) obj).element("value");
						hash.put(key.getText(), value.getText());
					}
				}
				Quote q = new Quote();
				q.setAuthor(hash.get("AUTHOR"));
				q.setQuote(hash.get("QUOTE"));
				return q;
			}
		} catch (XPathException e) {
			Element elem = (Element) rootElement.selectSingleNode("//faultstring");
			throw new RemoteException(elem.getText());
		} catch (Exception e) {
			MiddlewareUtil.encapsulateException(e);
		}
		return null;
	}

	@Override
	public String toSOAP(String operation, Object... parameters) {
		String body = "<tns:getQuote xmlns:tns=\"http://comp\" xmlns:types=\"http://comp/encodedTypes\">" +
		"<HTMLformat xsi:type=\"xsd:boolean\">false</HTMLformat></tns:getQuote>";

		return String.format("%s\n%s\n%s\n%s\n%s\n%s\n",
				TEMPLATE_XML_DECLARATION,
				TEMPLATE_HEADER_ENV,
				TEMPLATE_HEADER_BODY,
				body,
				TEMPLATE_TAIL_BODY,
				TEMPLATE_TAIL_ENV);
	}

}
